package com.lsl.controller;

import com.lsl.entity.Blog;
import com.lsl.entity.Result;
import com.lsl.dto.UserDTO;
import com.lsl.feign.UserFeignClient;
import com.lsl.service.BlogService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/blog-service")
public class MyBlogController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/getBlog/uid/{uid}")
    public Result<List<Blog>> getBlogsByUserId(@PathVariable String uid) {
        Result<UserDTO> userResult = userFeignClient.getUserById(uid);
        if (userResult == null || userResult.getData() == null) {
            return Result.error(404, "目标用户查询失败");
        }
        return Result.success(blogService.lambdaQuery()
                .eq(Blog::getAuthor, userResult.getData().getUsername())
                .list());
    }

    @PostMapping("/createBlog")
    public Result<Boolean> createBlog(@RequestBody Blog blog) {
        return Result.success(blogService.save(blog));
    }

    @PostMapping("/editBlog")
    public Result<Boolean> editBlog(@RequestBody Blog blog) {
        return Result.success(blogService.updateById(blog));
    }

    @DeleteMapping("/deleteBlog/uid/{uid}")
    public Result<Boolean> deleteBlogsByUserId(@PathVariable String uid) {
        Result<UserDTO> userResult = userFeignClient.getUserById(uid);
        if (userResult == null || userResult.getData() == null) {
            return Result.success(false);
        }
        return Result.success(blogService.lambdaUpdate()
                .eq(Blog::getAuthor, userResult.getData().getUsername())
                .remove());
    }

}
